package com.glodon.spring.controller;

import java.awt.*;
import java.io.PrintWriter;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.glodon.utils.service.StringRedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.github.bingoohuang.patchca.color.ColorFactory;
import com.github.bingoohuang.patchca.custom.ConfigurableCaptchaService;
import com.github.bingoohuang.patchca.filter.predefined.*;
import com.github.bingoohuang.patchca.utils.encoder.EncoderHelper;
import com.github.bingoohuang.patchca.word.RandomWordFactory;

/**
 * Created by Administrator on 2017-4-5.
 */
@Controller
public class CaptchaController {
    
    private static final Logger log = LoggerFactory.getLogger(CaptchaController.class);
    
    private static ConfigurableCaptchaService cs = new ConfigurableCaptchaService();
    
    private static Random random = new Random();


    @Autowired
    private StringRedisService redisService;

    static {
        
        cs.setColorFactory(new ColorFactory()
        {
            
            public Color getColor(int x) {
                
                int[] c = {25, 60, 170};
                int i = random.nextInt(c.length);
                for (int fi = 0; fi < c.length; fi++) {
                    
                    if (fi == i) {
                        c[fi] = random.nextInt(71);
                    } else {
                        c[fi] = random.nextInt(256);
                    }
                }
                return new Color(c[0], c[1], c[2]);
            }
        });
        
        RandomWordFactory wf = new RandomWordFactory();
        wf.setCharacters("123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
        wf.setMaxLength(4);
        wf.setMinLength(4);
        cs.setWordFactory(wf);
    }
    
    protected void setResponseHeaders(HttpServletResponse response) {
        response.setContentType("image/jpeg");
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        long time = System.currentTimeMillis();
        response.setDateHeader("Last-Modified", time);
        response.setDateHeader("Date", time);
        response.setDateHeader("Expires", time);
    }
    
    @RequestMapping(value = "/getpatchcaImage")
    public void getpatchcaImage(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        
        switch (random.nextInt(5)) {
            case 0:
                cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory()));
                break;
            case 1:
                cs.setFilterFactory(new MarbleRippleFilterFactory());
                break;
            case 2:
                cs.setFilterFactory(new DoubleRippleFilterFactory());
                break;
            
            case 3:
                cs.setFilterFactory(new WobbleRippleFilterFactory());
                break;
            
            case 4:
                cs.setFilterFactory(new DiffuseRippleFilterFactory());
                break;
            
        }
        
        HttpSession session = request.getSession(false);
        if (session == null) {
            session = request.getSession();
        }
        setResponseHeaders(response);
        String token = EncoderHelper.getChallangeAndWriteImage(cs, "png", response.getOutputStream());
        session.setAttribute("captchaToken", token);
        redisService.setExpire(session.getId(), token, 10);
        log.info("当前的 sessionId:{}, 验证码：{}", session.getId(), token);
        
    }
    
    /**
     * @author singer @Description: @param @param res @param @param resp @param @param out 参数说明 @return void 返回类型 @throws
     */
    @RequestMapping(value = "/validateCode")
    public void validateCode(HttpServletRequest res, HttpServletResponse resp, PrintWriter out) {
        boolean flag = false;
        String authcode = res.getParameter("code");
        String code = (String)res.getSession().getAttribute("captchaToken"); // 获取生成的验证码
        System.out.println(authcode + "," + code);
        if ((code.toUpperCase()).equals(authcode.toUpperCase())) {
            flag = true;
        } else {
            flag = false;
        }
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/plain;charset=utf-8");
        // 向叶面输出数据
        try {
            out.write(String.valueOf(flag));
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}
